/**
 * Created by wry on 2015/4/13.
 */
var Users = mongoose.model('user');
var async = require('async');
var neighbourActivity = mongoose.model('activity_neighbour');
var ugcIndex = mongoose.model('system_ugcIndex');
var Question = mongoose.model('question');
var questionReports = mongoose.model('question_reports');
var Community = mongoose.model('community');
var moment = require('moment');

exports.getBackOfficeActivityListService = function (communityId, page, level, desc, callback) {
    var index = (Number(page) - 1) * listPageSize;

    var opt = {
        //community: communityId,
        isValid: true
    };
    logger.debug(opt);

    if (level == '0') {
        opt.level = {$ne: 1}
    } else if (level == '1') {
        opt.level = Number(level);
    }
    if (communityId != 'all')
        opt.community = communityId;
    if (desc != 'all'){
        opt.desc = new RegExp(desc);
    };

    async.series([
        function (callbackInner) {
            neighbourActivity.find(opt).skip(index).limit(listPageSize).sort({
                displayOrder: -1,
                dateCreated: -1
            }).populate('community', 'communityName').populate('tag', 'value').populate('createdBy', 'userType nickName')
              .populate('replies.repliedBy', '_id community nickName images authenticationStatus')
              .populate('partake.user', '_id community nickName images authenticationStatus')
              .exec(callbackInner);
        },
        function (callbackInner) {
            neighbourActivity.count(opt, function (err, count) {
                callbackInner(err, Math.ceil(count / 30));
            });
        }
    ], callback);
};


exports.getBackOfficeActivityByFilterService = function (opt, callback) {

    if (opt['title'] != null) {
        opt['title'] = new RegExp(opt['title']);
    };
    logger.debug(opt);

    neighbourActivity.find(opt).sort({
        displayOrder: -1,
        dateCreated: -1
    }).populate('community', 'communityName')
      .populate('aroundCommunity', '_id communityName')
      .populate('tag', 'value').populate('createdBy', 'userType nickName').exec(callback);


};



/**
 * 活动置顶
 */
exports.moveActivityToTopService = function (opt, callback) {

    var Num = 0;

    async.series([
        function (callbackInner) {
            //neighbourActivity.find({
            //    community: opt.communityId,
            //    isValid: true
            //}).sort({displayOrder: -1}).limit(3).exec(function (err, results) {
            //    Num = (results[0].displayOrder ? results[0].displayOrder : 0) + 1;
            //    if (results.length == 3 && results[2].displayOrder > 0) {
            //        results[2].displayOrder = undefined;
            //        results[2].save(callbackInner);
            //    } else {
            //        callbackInner();
            //    }
            //});
            callbackInner();
        },
        function (callbackInner) {
            neighbourActivity.update({_id: opt.activityId}, {displayOrder: 3}, callbackInner)
        }
    ], callback);
};

/**
 * 活动取消置顶
 */
exports.cancelTopActivityService = function (input, callback) {
    neighbourActivity.findOne({_id: input.activityId}, function (err, result) {
        if (result.status) {
            result.displayOrder = 2;
        } else {
            result.displayOrder = 1;
        }
        result.save(callback);
    })
};


/**
 * 全部置顶
 */
exports.moveAllToTopService = function (opt, callback) {

    var Num = 0;

    async.series([
        function (callbackInner) {
            ugcIndex.find({
                community: opt.community
            }).sort({displayOrder: -1}).limit(3).exec(function (err, results) {
                Num = (results[0].displayOrder ? results[0].displayOrder : 0) + 1;
                if (results.length == 3 && results[2].displayOrder > 0) {
                    results[2].displayOrder = undefined;
                    results[2].save(callbackInner);
                } else {
                    callbackInner();
                }
            });
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: opt.id}, {displayOrder: Num}, callbackInner)
        }
    ], callback);
};

/**
 * 活动取消置顶
 */
exports.cancelTopAllService = function (input, callback) {
    ugcIndex.findOne({ugcId: input.id}, function (err, result) {
        result.displayOrder = undefined;
        result.save(callback);
    })
};


exports.getAllUgcService = function (page, communityId, callback) {

    var index = (Number(page) - 1) * listPageSize;
    var data = [];

    async.series([
        function (callback) {
            ugcIndex.find({
                community: communityId,
                category: {$ne: 'advertisement'}
            }).skip(index).limit(listPageSize).sort({
                displayOrder: -1,
                lastReply: -1
            }).exec(function (err, result) {
                if (result != null) {
                    async.eachSeries(result, function (ugc, callbackInner) {
                        if (ugc.category == 'neighbourActivity') {
                            neighbourActivity.findOne({_id: ugc.ugcId})
                                .populate('tag', 'category value _id')
                                .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                                .exec(function (err, activity) {
                                    if (activity != null) {
                                        activity._doc['displayOrder'] = ugc.displayOrder;
                                        data.push(activity);
                                    }
                                    callbackInner(err);
                                })
                        } else {
                            Question.findOne({_id: ugc.ugcId})
                                .populate('tag', 'category value _id')
                                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                                .populate('community', '_id communityName')
                                .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                                .exec(function (err, question) {
                                    if (question != null) {
                                        question._doc['displayOrder'] = ugc.displayOrder;
                                        data.push(question);
                                    }
                                    callbackInner(err);
                                })
                        }
                    }, function (err) {
                        callback(err, data);
                    })
                } else {
                    callback(null, data);
                }
            });
        },
        function (callback) {
            ugcIndex.count({
                community: communityId,
                category: {$ne: 'advertisement'}
            }, callback)
        }
    ], callback)
};

exports.backOfficeUpdateActivityService = function (input, callback) {

    var item = {
        'tag': input.tag,
        'title':input.title,
        'desc':input.desc
        //'deadline':input.deadline
    };

    async.series([
        function (callbackInner) {
            neighbourActivity.update({_id: input._id}, item, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: input._id}, {tag:input.tag}, callbackInner);
        }
    ], callback)
}

exports.backOfficeUpdateActivityServiceByModerator = function (input, callback) {
    var tags = input.tag.split(",");
    async.series([
        function (callbackInner) {
            neighbourActivity.update({_id: input._id},
                {
                    $set: {
                        'tag': tags
                    }
                }, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: input._id}, {$set: {'tag': tags}}, callbackInner);
        }
    ], callback)
}

exports.reports = function (input, callback) {
    questionReports.find({}, 'question reportUser').populate('question', 'desc').populate('reportUser', 'nickName').exec(function (err, result) {
        callback(err, result);
    })
}

exports.changeActivityLevelService = function (input, callback) {
    async.series([
        function (callbackInner) {
            neighbourActivity.update({_id: input.activityId}, {level: input.level}, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: input.activityId}, {level: input.level}, callbackInner);
        },
        function(callbackInner){

            if(input.level == 1) {

                var arg = {
                    userId: input.userId + '',
                    userRole: Number(input.userRole),
                    userActionType: 13
                };

                arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
                logger.debug(arg);
                scoreProxy.invoke('addScore', [arg], function (err, reply) {
                    try {
                        var data = JSON.parse(decodeURIComponent(reply));
                        if (err) {
                            logger.error('hessianInvokeAddScore-----2' + err.message);
                            callbackInner(null);
                        } else if (data.status != 0) {
                            logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
                            callbackInner(null);
                        } else {
                            callbackInner(null);
                        }
                    } catch (e) {
                        logger.error('hessianInvokeAddScore---4' + e);
                        callbackInner(e);
                    }
                });
            }else{
                callbackInner(null);
            }
        }
    ], callback);
};


exports.moveTopByIdService = function (input, callback) {

    async.eachSeries(input, function (ugc, callbackInner) {
        logger.debug(ugc._id);
        ugcIndex.update({ugcId: ugc.contentId}, {displayOrder:  moment().format('YYYYMMDDHHmmss')}, callbackInner);
        //ugcIndex.update({ugcId: ugc._id}, {displayOrder:  moment().format('YYYYMMDDHHmmss')}).exec(callbackInner);

    }, function (err) {
        callback(err, null);
    });
};

exports.cancelTopByIdService = function (input, callback) {


    //ugcIndex.findOne({ugcId: input.id}, function (err, result) {
    //    result.displayOrder = undefined;
    //    result.save(callback);
    //})
};


exports.exportJoinActivityService = function (req, callback) {

    var opt = {};
    var level = req.params.level;
    var desc = req.params.desc;

    if (level == '0') {
        opt.level = {$ne: 1}
    } else if (level == '1') {
        opt.level = Number(level);
    }

    if (desc != '__none'){
        opt.desc = new RegExp(desc);
    };

    opt.partake = {$exists: true, $not: {$size: 0}};

    async.series([
        function (callbackInner) {
            neighbourActivity.find(opt).populate('community', 'communityName').populate('createdBy', 'userType nickName')
                .populate('replies.repliedBy', '_id community nickName images authenticationStatus')
                .populate('partake.user', '_id community nickName images authenticationStatus')
                .sort({
                    displayOrder: -1,
                    dateCreated: -1
                })
                .exec(function (err, result) {
                    callbackInner(err, result);
                });
        }
    ], callback);
};

